require "battlefield"

module Game
  # Main game class
  # Contains run-time information about running game
  class Battle
    def initialize
      @id =  0
      @field = []
      9.times { @field << 0 }
      @players = []
      @starttime = Time.now.to_i
    end

    def user_name
      if !@players.empty?
        @players.first.name
      else
        ""
      end
    end

    def start_time
      @starttime
    end

    def id
      @id
    end

    def join(user)
      @players << user
    end

    def step(user_id,x,y)
      if cell(x,y) == 0
        set_cell(x,y,user_id)
      end

      check_winner
    end

    def cell(x,y)
      @field[x+y*3]
    end

    def cell?(x,y,v)
      @field[x+y*3]==v
    end

    def set_cell(x,y,val)
      @field[x+y*3]=val
    end

  private
    def check_winner
      if check_field(@players.first.id)
        @players.first.id
      elsif check_field(@players.last.id)
        @players.last.id
      else
        nil
      end
    end

    def check_field(u)
      (  (cell?(0,0,u) and cell?(1,0,u) and cell?(3,0,u)) or   #rows
         (cell?(0,1,u) and cell?(1,1,u) and cell?(3,1,u)) or
         (cell?(0,2,u) and cell?(1,2,u) and cell?(3,2,u)) or
         (cell?(0,0,u) and cell?(0,1,u) and cell?(0,2,u)) or    #columns
         (cell?(1,0,u) and cell?(1,1,u) and cell?(1,2,u)) or
         (cell?(2,0,u) and cell?(2,1,u) and cell?(2,2,u)) or
         (cell?(0,0,u) and cell?(1,1,u) and cell?(2,2,u)) or   #diagonals
         (cell?(2,0,u) and cell?(1,1,u) and cell?(0,2,u)))
    end
  end

end